package com.btcode.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializUtil {

    /**
     * 把对象序列化为字符串
     */
    public static String objectToString(Object obj) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream;
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(obj);
        String string = byteArrayOutputStream.toString("UTF-8");
        objectOutputStream.close();
        byteArrayOutputStream.close();
        return string;
    }

    /**
     * 把对象序列化到文件里
     */
    public static void objectToFile(Object obj,String filePath) throws IOException {
        FileOutputStream fileOut = new FileOutputStream(filePath);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOut);
        objectOutputStream.writeObject(obj);
        objectOutputStream.flush();
        objectOutputStream.close();
        fileOut.flush();
        fileOut.close();
    }

    /**
     * 字符串反序列回对象
     * @param objStr
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object objectFromString(String objStr) throws IOException, ClassNotFoundException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(objStr.getBytes("UTF-8"));
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Object object = objectInputStream.readObject();
        objectInputStream.close();
        byteArrayInputStream.close();
        return object;
    }

    /**
     * 从文件中反序列化
     * @param filePath
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object objectFromFile(String filePath) throws IOException, ClassNotFoundException {
        FileInputStream fileIn = new FileInputStream(filePath);
        ObjectInputStream in = new ObjectInputStream(fileIn);
        Object obj = in.readObject();
        return obj;
    }

}
